package com.dataaccess.dataaccess.web.service;


import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.dataaccess.dataaccess.common.base.BaseService;
import com.dataaccess.dataaccess.support.model.RespEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;

/**
 * @Author: YangYu
 * @ClassName: AutoNetworkAlarmDeviceDataChangedService
 * @Date: Created in 10:14 2021/1/21
 * @Description: 水泵服务
 */
@Service
public class WaterPumpService extends BaseService {


    @Resource
    private WaterPumpAsyncService waterPumpAsyncService;
    @Resource
    private AsyncService asyncService;
    /**
     * @Author YangYu
     * @Description 回调地址：设备数据变化，订阅后推送设备数据变化通知
     * @Date Created in 10:19 2021/1/21
     * @Param [s]
     */
    public RespEntity deviceDataChanged(JSONObject jsonParam)  {
        //字符串转大写
        String data = jsonParam.getStr("code").toUpperCase();
        //心跳+报警数据一起发过来
        if (data.length() == 114) {
            String flag = data.substring(12, 14);
            if (flag.equals("AA")) {
                String subData01 = data.substring(0, 18);
                String subData02 = data.substring(18);
                send(subData01);
                send(subData02);
            } else if (flag.equals("10")) {
                String subData01 = data.substring(0, 96);
                String subData02 = data.substring(96);
                send(subData01);
                send(subData02);
            }
        } else {
            send(data);
        }
        return RespEntity.success();
    }

    public RespEntity send(String data) {
        //标识
        String flag = data.substring(12, 14);
        //正常数据集合
        JSONObject object = new JSONObject();
        if (data.substring(0, 4).equals("4141")){
            //心跳数据
            if (flag.equals("AA")) {
                //模块编码
                String number = hex16To10Two(data.substring(4, 12));
                JSONArray jsonArray = new JSONArray();
                object.put("paraminfo", jsonArray);
                object.put("deviceClassify", "10");
                object.put("number", number);
                object.put("time", DateUtil.now());
            }
            else if (flag.equals("10")) {
                String alarmTypeName = "";
                String time = DateUtil.now();
                String contentVoltage = "";
                //数据头
                String dataHeader = data.substring(0, 4);
                //模块编码
                String number = hex16To10Two(data.substring(4, 12));
                //实时数据-A相电压
                String substring4 = data.substring(14, 18);
                String aVoltage = hex16To10(data.substring(14, 18))+"";
                //实时数据-B相电压
                String substring5 = data.substring(18, 22);
                String bVoltage = hex16To10(data.substring(18, 22))+"";
                //实时数据-C相电压
                String substring6 = data.substring(22, 26);
                String cVoltage = hex16To10(data.substring(22, 26))+"";
                //过压设定值
                String voltageSetValue = hex16To10(data.substring(26, 30))+"";
                //三相电压故障报警信息
                String alarmVoltage = data.substring(30, 34);
                String one = HexToBin(alarmVoltage.substring(0, 2))+"";
                String two = HexToBin(alarmVoltage.substring(2, 4))+"";

                JSONObject jsonObjectN = new JSONObject();
                //解析报警数据
                //电压报警-------------------------------------------------------------------------------------------------------------------------------
                if (one.substring(0, 1).equals("1")) {
                    contentVoltage += "";
                }
                if (one.substring(1, 2).equals("1")) {
                    contentVoltage += ",B相缺相";
                }
                if (one.substring(2, 3).equals("1")) {
                    contentVoltage += ",B相欠压";
                }
                if (one.substring(3, 4).equals("1")) {
                    contentVoltage += ",B相过压";
                }
                if (one.substring(4, 5).equals("1")) {
                    contentVoltage += "";
                }
                if (one.substring(5, 6).equals("1")) {
                    contentVoltage += ",A相缺相";
                }
                if (one.substring(6, 7).equals("1")) {
                    contentVoltage += ",A相欠压";
                }
                if (one.substring(7, 8).equals("1")) {
                    contentVoltage += ",A相过压";
                }

                if (two.substring(0, 1).equals("1")) {
                    contentVoltage += "";
                }
                if (two.substring(1, 2).equals("1")) {
                    contentVoltage += "";
                }
                if (two.substring(2, 3).equals("1")) {
                    contentVoltage += "";
                }
                if (two.substring(3, 4).equals("1")) {
                    contentVoltage += "";
                }
                if (two.substring(4, 5).equals("1")) {
                    contentVoltage += "";
                }
                if (two.substring(5, 6).equals("1")) {
                    contentVoltage += ",C相缺相";
                }
                if (two.substring(6, 7).equals("1")) {
                    contentVoltage += ",C相欠压";
                }
                if (two.substring(7, 8).equals("1")) {
                    contentVoltage += ",C相过压";
                }
                if (!alarmVoltage.equals("0000")) {
                    alarmTypeName = "电压故障报警";
                    if (contentVoltage.substring(0, 1).equals(",")) {
                        contentVoltage = contentVoltage.substring(1);
                    }
                    waterPumpAsyncService.sendAlarm(number, time, alarmTypeName, contentVoltage);
                }

                //控制柜故障状态---------------------------------------------------------------------------------------------------------------
                String controlFaultStatus1 = data.substring(34,36);
                String controlFaultStatus = data.substring(34,36).equals("01") ? "控制柜信息：有故障" : "控制柜信息：无故障";
                String controlFaultStatus2 = data.substring(34,36).equals("01") ? "1" : "2";
                //报警
                if (controlFaultStatus1.equals("01")) {
                    alarmTypeName = "控制柜故障报警";
                    waterPumpAsyncService.sendAlarm(number, time, alarmTypeName, controlFaultStatus);
                }
                if (controlFaultStatus2.equals("1")){
                    alarmTypeName = "消防泵监测";
                    waterPumpAsyncService.sendAlarm(number, time, alarmTypeName, controlFaultStatus);
                }
                //控制柜手自动状态---------------------------------------------------------------------------------------------------------------
                String controlHandleAutoState = data.substring(36, 38);
                String controlHandleAutoStateContext = "";
                if (controlHandleAutoState.equals("01")) {
                    controlHandleAutoStateContext = "控制柜手自动状态：自动";
                    alarmTypeName = "消防泵监测";
                    waterPumpAsyncService.sendAlarm(number, time, alarmTypeName, controlHandleAutoStateContext);
                } else if (controlHandleAutoState.equals("02")) {
                    controlHandleAutoStateContext = "控制柜手自动状态：手动";
                    alarmTypeName = "消防泵监测";
                    waterPumpAsyncService.sendAlarm(number, time, alarmTypeName, controlHandleAutoStateContext);
                }else if (controlHandleAutoState.equals("04")) {
                    controlHandleAutoStateContext = "控制柜手自动状态：停止";
                    alarmTypeName = "消防泵监测";
                    waterPumpAsyncService.sendAlarm(number, time, alarmTypeName, controlHandleAutoStateContext);
                }
                //存储控制柜故障状态和控制柜手自动状态
                JSONObject jsonParamN = new JSONObject();
                jsonParamN.put("number", number);
                jsonParamN.put("controlCabinetStatus", controlFaultStatus2);
                jsonParamN.put("controlCabinetHandleStatus", controlHandleAutoStateContext);
                restPostOrGet(jsonParamN, "firefightingiot", "updateWaterPumpInfo", "device","post");

                String switchOutputStatus = data.substring(38, 40).equals("01") ? "开关量输出状态：闭合" : "开关量输出状态：打开";

                //电流报警---------------------------------------------------------------------------------------------------------------
                //实时数据-A相电流
                String aElectricCurrent1 = data.substring(40,44);
                String aElectricCurrent = hex16To10(data.substring(40, 44)) + "";
                //实时数据-B相电流
                String bElectricCurrent1 = data.substring(44,48);
                String bElectricCurrent = hex16To10(data.substring(44, 48)) + "";
                //实时数据-C相电流
                String cElectricCurrent1 = data.substring(48,52);
                String cElectricCurrent = hex16To10(data.substring(48,52)) + "";
                //电流过载设定值
                String electricCurrentSetValue1 = data.substring(52,56);
                String electricCurrentSetValue = hex16To10(data.substring(52,56)) + "";
                //电流报警信息
                String currentAlarmInformation = data.substring(56, 58);
                String currentAlarmInfoBin = HexToBin(currentAlarmInformation);
                String overCurrentInfo = "";
                //C相过流 1 报警 , 0 正常
                String cOverCurrent = currentAlarmInfoBin.substring(3, 4);
                //B相过流 1 报警 , 0 正常
                String bOverCurrent = currentAlarmInfoBin.substring(5, 6);
                //A相过流 1 报警 , 0 正常
                String aOverCurrent = currentAlarmInfoBin.substring(7, 8);
                if (aOverCurrent.equals("1")) {
                    overCurrentInfo += "，A相过流";
                }
                if (bOverCurrent.equals("1")) {
                    overCurrentInfo += "，B相过流";
                }
                if (cOverCurrent.equals("1")) {
                    overCurrentInfo += "，C相过流";
                }

                overCurrentInfo = overCurrentInfo!=null && !overCurrentInfo.equals("") ? overCurrentInfo.substring(1) : "";
                if (!currentAlarmInformation.equals("00")) {
                    alarmTypeName = "电流故障报警";
                    waterPumpAsyncService.sendAlarm(number, time, alarmTypeName, overCurrentInfo);
                    //异步更新设备状态
                    jsonParamN.put("state","2");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }else {
                    //异步更新设备状态
                    jsonParamN.put("state","1");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }


                //温度报警---------------------------------------------------------------------------------------------------------------
                //实时数据-温度
                String temperature1 = data.substring(58, 62);
                String temperature = hex16To10(data.substring(58, 62)) + "";
                //过温设定值
                String temperatureSetValue1 = data.substring(62, 64);
                String temperatureSetValue = hex16To10(data.substring(62, 64)) + "";
                //温度报警信息
                String temperatureAlarmInformation = data.substring(64, 66).equals("01") ? "温度信息：过温" : "温度信息：正常";
                if (!data.substring(64, 66).equals("00")) {
                    alarmTypeName = "温度故障报警";
                    waterPumpAsyncService.sendAlarm(number, time, alarmTypeName, temperatureAlarmInformation);
                    //异步更新设备状态
                    jsonParamN.put("state","2");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }else {
                    //异步更新设备状态
                    jsonParamN.put("state","1");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }

                //漏电报警---------------------------------------------------------------------------------------------------------------
                //实时数据-漏电
                String electricLeakage1 = data.substring(66, 70);
                String electricLeakage = hex16To10(data.substring(66, 70)) + "";
                //漏电报警设定值
                String electricLeakageSetValue1 = data.substring(70, 74);
                String electricLeakageSetValue = hex16To10(data.substring(70, 74)) + "";
                //漏电报警信息
                String leakageAlarmInformation = data.substring(74, 76).equals("01") ? "漏电报警" : "无漏电";
                if (!data.substring(74, 76).equals("00")) {
                    alarmTypeName = "漏电故障报警";
                    waterPumpAsyncService.sendAlarm(number, time, alarmTypeName, leakageAlarmInformation);
                    //异步更新设备状态
                    jsonParamN.put("state","2");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }else {
                    //异步更新设备状态
                    jsonParamN.put("state","1");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }


                //平时数据
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name","A相电压");
                jsonObject.put("value",aVoltage);
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("name","B相电压");
                jsonObject1.put("value",bVoltage);
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("name","C相电压");
                jsonObject2.put("value",cVoltage);
                JSONObject jsonObject3 = new JSONObject();
                jsonObject3.put("name","A相电流");
                jsonObject3.put("value",aElectricCurrent);
                JSONObject jsonObject4 = new JSONObject();
                jsonObject4.put("name","B相电流");
                jsonObject4.put("value",bElectricCurrent);
                JSONObject jsonObject5 = new JSONObject();
                jsonObject5.put("name","C相电流");
                jsonObject5.put("value",cElectricCurrent);
                JSONObject jsonObject6 = new JSONObject();
                jsonObject6.put("name","温度");
                jsonObject6.put("value",temperature);
                JSONObject jsonObject7 = new JSONObject();
                jsonObject7.put("name","漏电");
                jsonObject7.put("value",electricLeakage);
                JSONArray jsonArray = new JSONArray();
                jsonArray.add(jsonObject);
                jsonArray.add(jsonObject1);
                jsonArray.add(jsonObject2);
                jsonArray.add(jsonObject3);
                jsonArray.add(jsonObject4);
                jsonArray.add(jsonObject5);
                jsonArray.add(jsonObject6);
                jsonArray.add(jsonObject7);
                //组装alarmType和content
                //三相电压无报警，控制柜故障 = alarmTypeName（控制柜故障）
                /*if (alarmVoltage.equals("0000") && controlFaultStatus1.equals("01")) {
                    alarmTypeName = "控制柜故障报警";
                } else if (alarmVoltage.equals("0000") && controlFaultStatus1.equals("00") && !currentAlarmInformation.equals("00")) {
                    alarmTypeName = "电流故障报警";
                }else if (alarmVoltage.equals("0000") && controlFaultStatus1.equals("00") && currentAlarmInformation.equals("00") && !data.substring(64, 66).equals("00")) {
                    alarmTypeName = "温度故障报警";
                }else if (alarmVoltage.equals("0000") && controlFaultStatus1.equals("00") && currentAlarmInformation.equals("00") && data.substring(64, 66).equals("00") && !data.substring(74, 76).equals("00")) {
                    alarmTypeName = "漏电故障报警";
                }*/
                //电压
                /*if (!alarmVoltage.equals("0000")) {
                    content += "，电压A:"+aVoltage+";电压B:"+bVoltage+":电压C:"+cVoltage;
                }
                //控制柜故障状态
                if (controlFaultStatus1.equals("01")) {
                    content += "，"+controlFaultStatus;
                }
                //电流报警信息
                if (!currentAlarmInformation.equals("00")) {
                    content += "，"+overCurrentInfo;
                }
                //温度报警信息
                if (data.substring(64, 66).equals("01")) {
                    content += "，"+temperatureAlarmInformation;
                }
                //漏电报警信息
                if (data.substring(74, 76).equals("01")) {
                    content += "，"+leakageAlarmInformation;
                }*/

                /*jsonObjectN.put("deviceClassify", "8");
                jsonObjectN.put("number", number);
                jsonObjectN.put("interfaceType", "1");
                jsonObjectN.put("alarmStr", "alarmStr");
                jsonObjectN.put("alarmtime", time);
                jsonObjectN.put("time", time);
                jsonObjectN.put("paraminfo", jsonArray);
                jsonObjectN.put("alarmTypeName", alarmTypeName);
                jsonObjectN.put("content", content != null && !content.equals("") ? content.substring(1) : "");*/
                object.put("paraminfo", jsonArray);
                object.put("deviceClassify", "10");
                object.put("number", number);
                object.put("time", time);
                //rest
                /*if (!alarmVoltage.equals("0000") || controlFaultStatus1.equals("01") || !currentAlarmInformation.equals("00") || data.substring(64, 66).equals("01") || data.substring(74, 76).equals("01")) {
                    fireFightingiot(jsonObjectN, "communication", "notificationAlarmHandel", "alarmInfo");
                }*/
            }
        }
        return fireFightingiot(object,"firefightingiot_data","normalInfo","device");
    }

    public static void main(String[] args) {
        String now = DateUtil.now();
        System.out.println(now);
    }
    //16进制数转二进制
    public static String HexToBin(String hex){
        Integer num = Integer.parseInt(hex, 16);
        String bin = Integer.toBinaryString(num);
        int length = bin.length();
        int max = 8;
        if (length < 8) {
            if (max - length == 1) {
                return "0" + bin;
            } else if (max - length == 2) {
                return "00" + bin;
            } else if (max - length == 3) {
                return "000" + bin;
            } else if (max - length == 4) {
                return "0000" + bin;
            } else if (max - length == 5) {
                return "00000" + bin;
            } else if (max - length == 6) {
                return "000000" + bin;
            } else if (max - length == 7) {
                return "0000000" + bin;
            } else {
                return "00000" + bin;
            }
        } else {
            return bin;
        }
    }

    //BCD码转为10进制串
    public static String bcd2Str(byte[] bytes){
        StringBuffer temp=new StringBuffer(bytes.length*2);

        for(int i=0;i<bytes.length;i++){
            temp.append((byte)((bytes[i]& 0xf0)>>>4));
            temp.append((byte)(bytes[i]& 0x0f));
        }
        return temp.toString().substring(0,1).equalsIgnoreCase("0")?temp.toString().substring(1):temp.toString();
    }

    private static byte toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }

    /**
     * 16进制转10进制
     * @param strHex
     * @return
     */
    public static String hex16To10Two(String strHex) {
        BigInteger lngNum = new BigInteger(strHex, 16);
        String hex = lngNum.intValue()+"";
        if (hex.length() == 1) {
            return "0000000"+hex;
        } else if (hex.length() == 2) {
            return "000000"+hex;
        }else if (hex.length() == 3) {
            return "00000"+hex;
        }else if (hex.length() == 4) {
            return "0000"+hex;
        }else if (hex.length() == 5) {
            return "000"+hex;
        }else if (hex.length() == 6) {
            return "00"+hex;
        }else if (hex.length() == 7) {
            return "0"+hex;
        }else {
            return hex;
        }
    }

    /**
     * 16进制转10进制
     * @param strHex
     * @return
     */
    public static int hex16To10(String strHex) {
        BigInteger lngNum = new BigInteger(strHex, 16);
        return lngNum.intValue();
    }

    /**
     * 年月日匹配
     * @param str
     * @return
     */
    public String getStr2(String str){
        if(str.length() == 1){
            return "0"+str;
        }
        return str;
    }

    /**
     * 16进制 转 ASCII码
     * @param “3030313030312d30303300000000000000000000”
     * @return 001001-003
     */
    public String convertHexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            if (!output.equals("00")) {
                //convert hex to decimal
                int decimal = Integer.parseInt(output, 16);
                //convert the decimal to character
                sb.append((char) decimal);

                temp.append(decimal);
            }
        }

        return sb.toString();

    }

}
